# coding: utf-8

import requests

from common.seven_moor.constant import (
    DOMAIN, ACCOUNT_ID,
    OUTBOUND_SERVICE_NO, BRIDGE_SERVICE_NO,
    AGENT_LIST, WEBCALL_CALLBACK_URL
)
from common.seven_moor.utils import Token


class Agent(object):
    """
    create by zhouhl 2018-01-09
    坐席类
    """

    @classmethod
    def query_user_state(cls, agent_id):
        """
        {'code': 200, 'data': {'flag': 'signout', 'state': '签出'}}
        {'code': 200, 'data': {'flag': '0', 'state': '空闲'}}
        {'code': 200, 'data': {'flag': '1', 'state': '忙碌'}}
        {'code': 200, 'data': {'flag': '2', 'state': '小休'}}
        {'code': 200, 'data': {'flag': '99', 'state': '后处理'}}
        """
        token = Token()
        authorization = token.create_authorization()
        sig = token.create_sig()

        url = DOMAIN.format('v20160818/user/queryUserState/' + ACCOUNT_ID)
        headers = {
            'Authorization': authorization
        }
        try:
            response = requests.post(
                url,
                headers=headers,
                params={'sig': sig},
                json={'exten': agent_id},
                timeout=3,
            )
            return response.json()
        except Exception as e:
            print(e)
            return {}

    @classmethod
    def query_idle_agent_num(cls):
        """
        查询在线且(空闲/非空闲)的客服
        """
        idle_agent_num, busy_agent_num = 0, 0
        for agent_id in AGENT_LIST:
            # 8004仅接呼入，故排除
            if agent_id in ('8004',):
                continue
            response = Agent.query_user_state(agent_id)
            flag = response.get('data', {}).get('flag')
            if flag == '0':
                idle_agent_num += 1
            elif flag in ['1', '2', '99']:
                busy_agent_num += 1

        return idle_agent_num, busy_agent_num

    @classmethod
    def query_idle_agents(cls):
        """
        created by chenhj at 09/03/2018
        返回所有空闲坐席
        """
        ret = []
        for agent_id in AGENT_LIST:
            response = Agent.query_user_state(agent_id)
            flag = response.get('data', {}).get('flag')
            if flag == '0':
                ret.append(agent_id)

        return ret

    @classmethod
    def list_agent_state(cls):
        """
        查看所有座席状态，供调试使用
        """
        for agent_id in AGENT_LIST:
            response = Agent.query_user_state(agent_id)
            print(agent_id, response)

        return None

    @classmethod
    def dialout(cls, agent_id, mobile, action_id):
        """
        指定座席外呼
        """
        token = Token()
        authorization = token.create_authorization()
        sig = token.create_sig()

        url = DOMAIN.format('v20160818/call/dialout/' + ACCOUNT_ID)
        headers = {
            'Authorization': authorization
        }
        data = {
            'FromExten': agent_id,
            'Exten': mobile,
            'ActionID': action_id
        }
        response = requests.post(
            url,
            headers=headers,
            params={'sig': sig},
            json=data
        )
        return response.json()


class WebCall(object):
    """
    create by zhouhl 2018-01-09
    WebCall类
    """

    @classmethod
    def make_web_call(cls, **kwargs):
        """
        座席外呼
        理论上来说应该使用webcall的异步方式
        Exten : 被叫号码

        v1的示例
        http://121.40.230.165/command?Action=Webcall&Account=N00000013811&PBX=bj.ykf.1.9&Timeout=20&ServiceNo=01000000565&Exten=被叫号码
        """
        token = Token()
        authorization = token.create_authorization()
        sig = token.create_sig()

        url = DOMAIN.format('v20160818/webCall/webCall/' + ACCOUNT_ID)

        headers = {
            'Authorization': authorization
        }
        data = {
            'Action': 'Webcall',
            'ServiceNo': OUTBOUND_SERVICE_NO,
            'Exten': kwargs.get('Exten'),
            'WebCallType': 'asynchronous',
            'CallBackUrl': WEBCALL_CALLBACK_URL,
            'CallBackType': 'get',
            'Timeout': 55,
        }
        try:
            response = requests.post(
                url,
                headers=headers,
                params={'sig': sig},
                json=data,
                timeout=3,
            )
            # 同步方式返回结果：{'Command': 'Response', 'Succeed': True, 'Message': '4', 'ActionID': 'Webcall0.05178073977244124', 'Response': 'Webcall'}
            # 异步方式返回结果：{'Command': 'Response', 'Succeed': True, 'ActionID': 'Webcall0.8475767439944453', 'Response': 'Webcall'}
            # 异步接口获得的信息
            # action_id =  Webcall0.8475767439944453
            # message =  3

            return response.json()
        except Exception as e:
            print(e)
            return {}


    @classmethod
    def bridge_web_call(cls, **kwargs):
        """
        桥接客户电话
        Exten : 主叫号码（先响铃）
        Variable : 被叫号码（后响铃）

        v1的示例
        http://121.40.230.165/command?Action=Webcall&Account=N00000013811&PBX=bj.ykf.1.9&Timeout=20&ServiceNo=01000009113&Exten=被叫号码（先响铃）&Variable=phoneNum:被加号码
        """
        token = Token()
        authorization = token.create_authorization()
        sig = token.create_sig()

        url = DOMAIN.format('v20160818/webCall/webCall/' + ACCOUNT_ID)

        headers = {
            'Authorization': authorization
        }
        data = {
            'Action': 'Webcall',
            'ServiceNo': BRIDGE_SERVICE_NO,
            'Exten': kwargs.get('Exten'),
            'Variable': 'phoneNum:' + kwargs.get('Variable'),
            'WebCallType': 'asynchronous',
            'CallBackUrl': WEBCALL_CALLBACK_URL,
            'CallBackType': 'get',
        }
        response = requests.post(
            url,
            headers=headers,
            params={'sig': sig},
            json=data
        )

        # 同步方式返回结果：{'Command': 'Response', 'Succeed': True, 'Message': '4', 'ActionID': 'Webcall0.3928486484971576', 'Response': 'Webcall'}
        # 异步方式放回结果：{'Command': 'Response', 'Succeed': True, 'ActionID': 'Webcall0.25460970739518807', 'Response': 'Webcall'}
        # 异步接口获得的信息
        # action_id =  Webcall0.25460970739518807
        # message =  4

        return response.json()


if __name__ == '__main__':

    # Agent.query_user_state('8000')

    print(Agent.query_idle_agent_num())

    # 座席外呼，Exten需要提供真实号码
    # print(WebCall.make_web_call(
    #     #Exten='18817877341',
    #     #Exten='13247639189',
    #     Exten='13421376954'
    # ))

    # 桥接客户电话
    # print(WebCall.bridge_web_call(
    #     Exten='18817877341',
    #     Variable='13421376954',
    # ))

    pass
